{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ergo\n",
    "import seaborn\n",
    "\n",
    "from ergo import Logistic, LogisticMixture\n",
    "from ergo.distributions.conditions import IntervalCondition, PercentileCondition\n",
    "from tqdm.autonotebook import tqdm\n",
    "from matplotlib import pyplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b676581438534590928b35e2d81e1cdc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(FloatProgress(value=0.0, max=1000.0), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def normalize(xs):\n",
    "    z = sum(xs)\n",
    "    return [x/z for x in xs]\n",
    "\n",
    "def sample_component():\n",
    "    return Logistic(loc=ergo.uniform(-1, 2), scale=abs(ergo.lognormal_from_interval(0.2, 3)))\n",
    "\n",
    "def sample_condition(dist):\n",
    "    case = ergo.random_choice([\"low_open\", \"bounded\", \"high_open\"])\n",
    "    if case == \"low_open\":\n",
    "        xmin = float(\"-inf\")\n",
    "        xmax = ergo.uniform(-3, 3)\n",
    "    elif case == \"bounded\":\n",
    "        xmin = ergo.uniform(-3, 0)                \n",
    "        xmax = xmin + ergo.uniform(0, 3)        \n",
    "    elif case == \"high_open\":\n",
    "        xmin = ergo.uniform(-3, 3)\n",
    "        xmax = float(\"+inf\")\n",
    "    p = actual_p(dist, xmin, xmax)\n",
    "    return IntervalCondition(p, xmin, xmax)\n",
    "\n",
    "def sample_conditions(dist):\n",
    "    num_conditions = ergo.random_choice([1, 2, 3, 5, 7])\n",
    "    conditions = [sample_condition(dist) for _ in range(num_conditions)]\n",
    "    return conditions\n",
    "\n",
    "def sample_mixture():\n",
    "    num_components = ergo.random_choice([1, 2, 3])\n",
    "    components = [sample_component() for _ in range(num_components)]\n",
    "    probs = normalize([ergo.uniform(0, 1) for _ in range(num_components)])\n",
    "    return LogisticMixture(components, probs)\n",
    "    \n",
    "def actual_p(dist, xmin, xmax):\n",
    "    cdf_at_min = dist.cdf(xmin) if not np.isneginf(xmin) else 0\n",
    "    cdf_at_max = dist.cdf(xmax) if not np.isposinf(xmax) else 1\n",
    "    return cdf_at_max - cdf_at_min\n",
    "\n",
    "def plot(dist, ax=None):\n",
    "    xs = np.linspace(-4, 4, 100)\n",
    "    ys = [float(mixture.pdf1(x)) for x in xs]\n",
    "    # pyplot.figure()\n",
    "    return seaborn.lineplot(xs, ys)\n",
    "    \n",
    "def model():\n",
    "    # 1. Sample a distribution with 1-3 peaks\n",
    "    true_dist = sample_mixture()\n",
    "\n",
    "    # 2. Sample 1-7 conditions\n",
    "    conditions = sample_conditions(true_dist)\n",
    "    \n",
    "    # 3. Fit a mixture to those conditions\n",
    "    fit_dist = LogisticMixture.from_conditions(conditions, num_components=3)\n",
    "    \n",
    "    # 4. Check that the conditions are satisfied\n",
    "    for condition in conditions:\n",
    "        fit = condition.describe_fit(fit_dist)\n",
    "        if fit[\"loss\"] > 0.000002:\n",
    "            print(true_dist)\n",
    "            print(fit_dist)\n",
    "            print(fit)     \n",
    "            for condition in conditions:\n",
    "                print(conditions)\n",
    "            ax = plot(true_dist)\n",
    "            plot(fit_dist, ax=ax)\n",
    "            raise Exception(\"Failed to fit\")\n",
    "\n",
    "for i in tqdm(range(1000)):\n",
    "    model()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
